<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 茂佳
 */
class MaojiaController extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));

        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            //'orderid' => createOrderId(),
            'orderid' => date("YmdHis",time()).mt_rand(10000,99999),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );
        $return = $this->orderadd( $parameter );

        $isMobile = isMobile();

        $data = array();
        $data['version'] = 'V1.0.0';
        $data['mch_id'] = $this->config['mch_id'];
        $data['nonce_str'] = md5(date("YmdHis",time()).mt_rand(10000,99999));
        $data['body'] = 'zf';
        $data['out_trade_no'] = $return['orderid'];
        $data['total_fee'] = $return['amount'] * 100;
        $data['spbill_create_ip'] = getIP();
        $data['notify_url'] = $return['notifyurl'];
        $data['return_url'] = $return['callbackurl'];
        $data['accountType'] = '1';
        $data['cardAttr'] = '2';
        $data['trade_type'] = 'trade.gateway.pay';

        ksort($data);
        $data['sign'] = strtoupper(md5(httpstr($data)."&key=".$this->config['signkey']));
        $res = curl_xml($this->config['gateway'], $data);
        $res = xmlToArray($res);
        //file_put_contents("a.txt", var_export($res, true));

        $code = $res['code_url'];
        if(!$code){
            if($res['return_msg']){
                $this->showmessage($res['return_msg'],['code'=>C("THIRDCODES.".$this->class)]);
            }
            $this->showmessage('获取支付链接失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        echo $code;
    }

    //数组转XML
    private function arrayToXml($arr){
        $xml = "<xml>";
        foreach ($arr as $key=>$val) {
            if ($key == 'total_fee'){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }

    public function postXmlCurl($url,$xml,$second=10) {
        //设置header
        $header[] = "Content-type: text/xml";
        //初始化curl
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        //设置header
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }


    //通知
    public function notifyurl(){
        //file_put_contents("a.txt",var_export($_POST,true)."\r\n\r\n");
        //file_put_contents("a.txt",var_export($_GET,true)."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", file_get_contents('php://input')."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", date("Y-m-d H:i:s",time())."\r\n\r\n", FILE_APPEND);

        $p = $origin = file_get_contents('php://input');

        //$p = '<xml><trade_type><![CDATA[trade.gateway.pay]]></trade_type><total_fee><![CDATA[3000]]></total_fee><transaction_id><![CDATA[5000290103012018111517032323704]]></transaction_id><out_trade_no><![CDATA[2018111517032323704]]></out_trade_no><mch_id><![CDATA[500029010301]]></mch_id><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><nonce_str><![CDATA[KLCv1tsFmxePtymz]]></nonce_str><sign><![CDATA[6A12A998D6BA2107B8B6EA0504ABF67D]]></sign></xml>';

        $p = xmlToArray($p);

        if(!$p || empty($p)){
            exit("wrong");
        }

        //获取订单信息
        $orderid = $p['out_trade_no'];
        $find = M("Order")->where(array("pay_orderid"=>$orderid))->find();
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(
            "server_return"=> $origin,
            "pay_orderid_rd"=>$p['transaction_id']
        ));

        /*
         *Array
                (
                    [trade_type] => trade.gateway.pay
                    [total_fee] => 3000
                    [transaction_id] => 5000290103012018111517032323704
                    [out_trade_no] => 2018111517032323704
                    [mch_id] => 500029010301
                    [result_code] => SUCCESS
                    [return_code] => SUCCESS
                    [nonce_str] => KLCv1tsFmxePtymz
                    [sign] => 6A12A998D6BA2107B8B6EA0504ABF67D
                )
         */

        //获取渠道信息
        $this->config = Channel::getInstance()->find(['code'=>$this->class]);

        $sign = $p['sign'];
        unset($p['sign']);

        ksort($p);

        $sign2 = strtoupper(md5(httpstr($p)."&key=".$this->config['signkey']));

        /*
        echo '<pre/>'; print_r($p);
        echo "sign: " .$sign ."<br/>";
        echo "sign2:".$sign2."<br/>";
        */
        if($sign != $sign2){
            exit("sign_wrong");
        }

        if($p['return_code'] !== 'SUCCESS' || $p['result_code'] !== 'SUCCESS'){
            exit("pay_fail");
        }

        $this->async($find['pay_orderid'],'success');
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}